/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    let node = root;
    let path = []
    while(node) {
        path.push(node.val)
        if(node.val == p.val) break
        if(node.val < p.val) node = node.right
        else if(node.val > p.val) node = node.left
    }
    node = root
    let i = 0
    let temp = null
    while(node) {
        if(node.val == path[i]) {
            temp = node
            i++
        }
        if(node.val == q.val) break
        if(node.val < q.val) node = node.right
        else if(node.val > q.val) node = node.left
    }
    return temp
};